package com.tuuzed.android.qrcode.internal.decode;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

import java.nio.charset.Charset;
import java.util.Hashtable;
import java.util.Vector;


public class BitmapDecoder {

    private MultiFormatReader mMultiFormatReader;

    private static class DefaultInstanceHolder {
        private static final BitmapDecoder defaultInstance = create();
    }

    public static BitmapDecoder getDefault() {
        return DefaultInstanceHolder.defaultInstance;
    }

    public static BitmapDecoder create() {
        return create(Charset.forName("utf-8"), null);
    }

    public static BitmapDecoder create(@NonNull Charset charset, Vector<BarcodeFormat> decodeFormats) {
        return new BitmapDecoder(charset, decodeFormats);
    }

    private BitmapDecoder(@NonNull Charset charset, Vector<BarcodeFormat> decodeFormats) {
        mMultiFormatReader = new MultiFormatReader();
        // 解码的参数
        Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2);
        // 可以解析的编码类型
        if (decodeFormats == null || decodeFormats.isEmpty()) {
            // 设置可扫描的类型
            decodeFormats = new Vector<>();
            decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
            decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
            decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
        }
        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
        // 设置解析的字符编码格式
        hints.put(DecodeHintType.CHARACTER_SET, charset.name());
        // 设置解析配置参数
        mMultiFormatReader.setHints(hints);
    }

    public Result getResult(@NonNull Bitmap src) throws NotFoundException {
        return getResult(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(src))));
    }

    public Result getResult(@NonNull BinaryBitmap src) throws NotFoundException {
        return mMultiFormatReader.decodeWithState(src);
    }
}
